﻿using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using BLL.Configuration;
using BLL.Security;

namespace Web.Infrastructure.Compression
{
    public partial class Compressor
    {
        public static bool IsReady;

        private IGlobalSettings _globalSettings
        {
            get
            {
                return DependencyResolver.Current.GetService<IGlobalSettings>();
            }
        }

        public void StartCompress()
        {
            // Prevert compress many times
            if (IsReady)
                return;
            if (!DependencyResolver.Current.GetService<IGlobalSettings>().Compress.IsEnabledForTemplate)
                return;
            var baseUrl = _globalSettings.Web.WebsiteLocation;

            var contentPath = HttpContext.Current.Server.MapPath("~/Content");

            var ticket = new FormsAuthenticationTicket(
                2,
                "Administrator",
                DateTime.Now,
                DateTime.Now.AddHours(12),
                false,
                ((byte)UserTypes.Administrator).ToString(CultureInfo.InvariantCulture));

            var cookie = new Cookie(_globalSettings.Security.AdminAuthenticationCookieName, FormsAuthentication.Encrypt(ticket));
            cookie.Domain = DependencyResolver.Current.GetService<IGlobalSettings>().Compress.Domain;
            cookie.Path = "/";

            foreach (var contentItems in _items.GroupBy(x => x.Area))
            {
                var writePath = contentPath;
                var area = contentItems.Key;
                if (!string.IsNullOrEmpty(area))
                {
                    writePath = Path.Combine(writePath, area);
                    if (!Directory.Exists(writePath))
                    {
                        Directory.CreateDirectory(writePath);
                    }
                }

                foreach (var contentItem in contentItems)
                {
                    var controllerFolderPath = Path.Combine(writePath, contentItem.Controller);
                    if (!Directory.Exists(controllerFolderPath))
                    {
                        Directory.CreateDirectory(controllerFolderPath);
                    }

                    var filePath = Path.Combine(controllerFolderPath, contentItem.Action);
                    filePath = filePath.TrimEnd('\\') + ".html";

                        var request = (HttpWebRequest)WebRequest.Create(baseUrl + contentItem.Url);
                        request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                        request.CookieContainer = new CookieContainer();
                        request.CookieContainer.Add(cookie);

                        try
                        {
                            var responce = (HttpWebResponse)request.GetResponse();

                            if (!responce.ContentType.Contains("application/json"))
                            {
                                var stream = new StreamReader(responce.GetResponseStream());

                                using (var fs = new StreamWriter(filePath))
                                {
                                    fs.WriteLine(stream.ReadToEnd());
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
        }
    }
}